const answersRawData = require('../mapping/answers-raw-data')
const manageAllSurveys = require('../mapping/manage-all-surveys')
const surveysRawData = require('../mapping/surveys-raw-data')
const { getSoleStr, logError } = require('../func/util')
const { getToken } = require('../mapping/access')
const questionType = Object.values(require('../constants/type'))

function middleCheckAccess(req, res, next) {
    const token = req.headers.usertoken
    const tokens = Object.values(getToken())
    if (tokens.includes(token)) {
        next()
    } else {
        res.status(401)
        res.send('请先登录')
    }
}

function getAllSurvey(req, res) {
    try {
        const data = []
        const surveys = manageAllSurveys.get()
        const allAnswerNum = answersRawData.countAllAnswerNum()

        surveys.forEach(s => {
            if (s.delete) return
            s.collect_num = allAnswerNum[s.id]
            data.push(s)
        })

        res.status(200)
        res.send({ data, msg: 'success' })
    } catch (error) {
        logError(error)
        res.status(500)
        res.send({ msg: '服务器未知错误' })
    }
}

function getDeletedSurvey(req, res) {
    try {
        const data = []
        const surveys = manageAllSurveys.get()
        const allAnswerNum = answersRawData.countAllAnswerNum()

        surveys.forEach(s => {
            if (!s.delete) return
            s.collect_num = allAnswerNum[s.id]
            data.push(s)
        })

        res.status(200)
        res.send({ data, msg: 'success' })
    } catch (error) {
        logError(error)
        res.status(500)
        res.send({ msg: '服务器未知错误' })
    }
}

function toggleSurveyOver(req, res) {
    try {
        const surveyId = req.body.id
        const surveys = manageAllSurveys.get()
        const i = surveys.findIndex(s => s.id == surveyId)
        if (i === -1) throw new NotFindIndexError('找不到问卷')
        surveys[i].over = !surveys[i].over
        manageAllSurveys.set(surveys)

        res.status(200)
        res.send({ msg: 'success' })
    } catch (e) {
        if (e instanceof NotFindIndexError) {
            res.status(404)
            res.send({ msg: e.message })
            return
        }
        logError(e)
        res.status(500)
        res.send({ msg: '服务器出现未知异常' })
    }
}

function createSurvey(req, res) {
    try {
        const survey = req.body

        const sNum = surveysRawData.countSurvey()
        survey.id = 's-' + sNum
        survey.create_time = new Date().getTime() + ''

        survey.questions.forEach((q, qi) => {
            if (!questionType.includes(q.type)) throw new SyntaxError('type')
            if (typeof q.title !== 'string') throw new SyntaxError('type')

            q.id = `q-${sNum}-${qi}`
            q.options?.forEach((o, i) => {
                q.options[i] = {
                    id: `op-${sNum}-${qi}-${i}`,
                    text: o,
                }
            })
            q.subTitles?.forEach((s, i) => {
                q.subTitles[i] = {
                    id: `sub-${sNum}-${qi}-${i}`,
                    text: s,
                }
            })
        })

        const surveys = manageAllSurveys.get()
        surveys.push({
            id: survey.id,
            title: survey.title,
            create_time: survey.create_time,
            over: false,
            delete: false,
        })

        surveysRawData.addSurvey(survey)
        manageAllSurveys.set(surveys)

        res.status(200)
        res.send({
            survey_id: survey.id,
            msg: 'success',
        })
    } catch (error) {
        if (error instanceof SyntaxError && error.message === 'type') {
            res.status(406)
            res.send({ msg: '问卷格式错误' })
            return
        }

        logError(error)
        res.status(500)
        res.send({ msg: '服务器抛出了异常' })
    }
}

function delSurvey(req, res) {
    try {
        const surveyId = req.body.id
        const surveys = manageAllSurveys.get()
        const i = surveys.findIndex(s => s.id == surveyId)

        if (i === -1) throw new NotFindIndexError('找不到问卷')
        surveys[i].delete = true
        manageAllSurveys.set(surveys)

        res.status(200)
        res.send({ msg: 'success' })
    } catch (e) {
        if (e instanceof NotFindIndexError) {
            res.status(404)
            res.send({ msg: e.message })
            return
        }
        logError(e)
        res.status(500)
        res.send({ msg: '服务器出现未知异常' })
    }
}

function restoreSurvey(req, res) {
    try {
        const surveyId = req.body.id
        const surveys = manageAllSurveys.get()
        const i = surveys.findIndex(s => s.id == surveyId)

        if (i === -1) throw new NotFindIndexError('找不到问卷')
        surveys[i].delete = false
        manageAllSurveys.set(surveys)

        res.status(200)
        res.send({ msg: 'success' })
    } catch (e) {
        if (e instanceof NotFindIndexError) {
            res.status(404)
            res.send({ msg: e.message })
            return
        }
        logError(e)
        res.status(500)
        res.send({ msg: '服务器出现未知异常' })
    }
}

function statAnswer(req, res) {
    try {
        const answers = answersRawData.getAnswers(req.params.id)

        res.send({
            data: answers,
            msg: 'success',
        })
    } catch (error) {
        logError(error)
        res.status(500)
        res.send('服务器出现未知异常')
    }
}

function getSurvey(req, res) {
    try {
        const id = req.params.id
        const surveys = manageAllSurveys.get()
        const i = surveys.findIndex(s => s.id === id)

        if (i === -1) throw new NotFindIndexError('问卷不存在')
        if (surveys[i].delete) throw new NotFindIndexError('问卷已被删除')

        res.status(200)
        res.send({
            data: surveysRawData.getSurvey(surveys[i].id),
            msg: 'success',
        })
    } catch (error) {
        if (error instanceof NotFindIndexError) {
            res.status(404)
            res.send({ msg: error.message })
            return
        }
        res.status(500)
        res.send({ msg: '服务器出现未知错误' })
    }
}

function replaceAnswer(req, res) {
    try {
        answersRawData.replaceAnswer(req.body)
        res.send({ msg: 'success' })
    } catch (error) {
        logError(error)
        res.status(500)
        res.send({ msg: '服务器出现异常' })
    }
}

function delAnswer(req, res) {
    try {
        const { survey_id, answer_id } = req.body
        if(typeof answer_id === 'undefined') throw new SyntaxError('no id')
        answersRawData.delAnswer(survey_id, answer_id)
        res.send({ msg: 'success' })
    } catch (error) {
        if (error instanceof SyntaxError && error.message === 'no id') {
            res.status(406)
            res.send({ msg: '未提供 answer_id' })
            return
        }
        logError(error)
        res.status(500)
        res.send({ msg: '服务器出现异常' })
    }
}

module.exports = {
    middleCheckAccess,
    getAllSurvey,
    getDeletedSurvey,
    toggleSurveyOver,
    createSurvey,
    delSurvey,
    restoreSurvey,
    statAnswer,
    getSurvey,
    replaceAnswer,
    delAnswer,
}
